//
//  UserAccount.swift
//  sinaWeiBo
//
//  Created by weixq on 15/8/3.
//  Copyright © 2015年 weixq. All rights reserved.
//

import UIKit

class UserAccount: NSObject, NSCoding {
    
    class var userLogon: Bool {
        return loadAccount() != nil
    }
    
    /// 用于调用access_token，接口获取授权后的access token
    var access_token: String?
    /// access_token的生命周期，单位是秒数 - 准确的数据类型是`数值`
    var expires_in: NSTimeInterval = 0{
        didSet{
        expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
     /// 过期日子
    var expiresDate: NSDate?
    
    /// 当前授权用户的UID
    var uid: String?
    
    /// 友好显示名称
    var name: String?
    /// 用户头像地址（大图），180*180像素
    var avatar_large: String?
    
    init(dict: [String: AnyObject]) {
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
        UserAccount.userAccount = self
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    /// 对象描述信息
    override var description: String {
        let properties = ["access_token", "expires_in", "uid", "expiresDate", "name", "avatar_large"]

        return "\(dictionaryWithValuesForKeys(properties))"
    }
    
    // 加载用户信息
    func loadUserInfo(finish:(error: NSError?) -> ()){
        // 获取网络数据
      
        NetworkTools.sharedTools.loadUserInfo(uid!) { (result, error) -> () in
      
            if error !=  nil{
                finish(error: error)
                return
            }
            
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            
            self.saveAccount()
            print(self)
            finish(error: nil)
        }
       
    }
    
    
    // MARK: - 归档 & 解档的方法
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last!.stringByAppendingPathComponent("account.plist")
    
    /// 保存用户账号
    func saveAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: UserAccount.accountPath)
    }
    
    // 如果没有登录返回空
    // 如果 token 过期，返回空
    
    // 静态的用户账户属性
   private static var userAccount: UserAccount?
   class func loadAccount() -> UserAccount?{
    
        if userAccount == nil {
            userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath) as? UserAccount
        }
    
        if let date = userAccount?.expiresDate where date.compare(NSDate()) == NSComparisonResult.OrderedAscending{
            userAccount = nil
        }
    
        return userAccount
    }
    
    
    // 归档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    
    // 解档
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }

}
